package vip.liux.contracts.models.point;

import org.springframework.stereotype.Component;
import vip.liux.contracts.repositories.point.IPointsRuleRepository;
import vip.liux.contracts.repositories.point.IPointsTransactionRepository;
import vip.liux.contracts.shared.enums.point.PointRuleType;
import vip.liux.core.exception.BusinessException;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;

@Component
public class PointsRuleDomainService {
    private final IPointsRuleRepository pointsRuleRepository;
    private final IPointsTransactionRepository transactionRepo;

    public PointsRuleDomainService(IPointsRuleRepository pointsRuleRepository, IPointsTransactionRepository transactionRepo) {
        this.pointsRuleRepository = pointsRuleRepository;
        this.transactionRepo = transactionRepo;
    }

    public PointsRule validateRule(String ruleCode, Long userId, BigDecimal point) {

        PointsRule rule = pointsRuleRepository.findEnabledByRuleCode(ruleCode).orElseThrow(() -> new BusinessException("规则编号:" + ruleCode + " 不存在或未启用"));

        if (rule.getRuleType() == PointRuleType.ACQUIRE) {
            if (rule.getDailyLimit() != null) {
                BigDecimal todayUsage = transactionRepo.sumTodayPointsByUserAndRule(
                        userId,
                        LocalDate.now().atStartOfDay(),
                        LocalDateTime.now()
                );

                if (todayUsage != null && todayUsage.compareTo(rule.getDailyLimit().add(point)) > 0) {
                    throw new BusinessException("今日领取使用已达上限: " + rule.getDailyLimit());
                }
            }
        }

        return rule;
    }
}
